package com.fmblzf.library.text;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.TextView;

import com.fmblzf.library.util.UtilsTool;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2015/10/15.
 */
public class TextViewBackColor extends TextView {
    //背景画笔
    private Paint backPaint = new Paint();
    //文本画笔
    private Paint textPaint = getPaint();
    //文本绘制时，的基准线
    private int baseline = 0;
    //分割符号
    String splitSymbol = null;
    //符号画笔
    private Paint symbolPaint = null;
    //字符宽度
    private int splitSymbolWidth = 0;
    //文本分割后的数组
    private String[] arrayString = null;
    //分割后各个字符串的宽度
    private int[] arrayWidth = null;
    //圆角角度
    private int round = 5;
    //文字距离边框的内边距
    private int padding = 10;
    //上下文
    private Context mContext;

    public void setSeconds(long seconds) {
        this.seconds = seconds;
    }

    public long getSeconds() {
        return seconds;
    }

    //将时间转化成秒
    private long seconds = 0L;

    public boolean isTimeOver() {
        return timeOver;
    }

    //时间结束
    private boolean timeOver = false;

    public void setViewText(String text){
        setText(text);
        stringSplit();
        calculateSize();
        setCalculateWidth();
        invalidate();
    }

    public TextViewBackColor(Context context) {
        this(context, null, 0);
//        initWidget();
    }

    public TextViewBackColor(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
//        initWidget();
    }

    public TextViewBackColor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initWidget();
    }

    /**
     * 初始化控件
     */
    public void initWidget(){
        backPaint.setColor(Color.parseColor("#797979"));
        textPaint.setColor(Color.WHITE);
        symbolPaint = new Paint(getPaint());
        symbolPaint.setColor(Color.parseColor("#797979"));
    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);

//        if(arrayString == null){
//            stringSplit();
//        }
//        if(arrayWidth == null){
//            calculateSize();
//        }
        if(arrayWidth == null || arrayWidth.length==0)
            return ;
        RectF rect = null;
        int width = 0;
        for(int i = 0 ; i <arrayWidth.length;i++ ){
            rect = new RectF(width,0,width+arrayWidth[i]+2*padding,getHeight());
            canvas.drawRoundRect(rect, round,round, backPaint);
            width += padding;
            canvas.drawText(arrayString[i],width,baseline,textPaint);
            width += arrayWidth[i]+padding;
            if(i < arrayWidth.length-1) {
                //画特殊的分隔符
                width += padding;
                canvas.drawText(splitSymbol, width, baseline, symbolPaint);
                width += splitSymbolWidth;//字符宽度
                width += padding;
            }
        }
//        width += (arrayWidth.length-1)*2;
        canvas.restore();
        //super.onDraw(canvas);
    }

    /**
     * 将文本按照对应的字符，分割成数组
     */
    private void stringSplit(){
        if(getTag() == null || getText() == null || "".equals(getText().toString()))
            return;
        splitSymbol = getTag().toString();
        arrayString = getText().toString().split(splitSymbol);
    }

    /**
     * 计算各个文本的宽度
     */
    private void calculateSize(){
        if(arrayString == null || arrayString.length == 0)
            return ;
        Rect bounds = new Rect();
        if(arrayWidth == null || arrayWidth.length<arrayString.length) {
            arrayWidth = new int[arrayString.length];
        }
        for (int i = 0;i<arrayString.length;i++){
            //if(arrayWidth[i] == 0) {
            getPaint().getTextBounds(arrayString[i], 0, arrayString[i].length(), bounds);
            arrayWidth[i] = arrayWidth[i] > bounds.width() ? arrayWidth[i] : bounds.width();
            //}
        }
        textPaint.getTextBounds(splitSymbol, 0, splitSymbol.length(), bounds);
        splitSymbolWidth = bounds.width();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();
        baseline = (getMeasuredHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;

        if(getText() != null && getText().toString().length()>0) {
            //if(arrayString == null){
            stringSplit();
            //}
            //if(arrayWidth == null){
            calculateSize();
            //}

            setCalculateWidth();
        }
    }

    /**
     * 设置控件的宽度
     */
    private void setCalculateWidth(){
        int width = 0;

        for(int i = 0;i<arrayWidth.length;i++){
            width += arrayWidth[i];
        }
        //加上每段文字中的左右间距
        width += arrayWidth.length*padding*2;
        //加上特殊符号的宽度和间距
        width += (arrayWidth.length-1)*(splitSymbolWidth+padding*2);
        setWidth(width);
    }

    /**
     * 消息机制，刷新控件信息
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            seconds--;
            String text = UtilsTool.convertSecondToTimeStr(seconds * 1000);
            setViewText(text);
        }
    };
    //定时器
    private Timer timer;
    //定时任务
    private TimerTask task = null;

    /**
     * 开始定时任务
     */
    public void start(){
        if(timer == null){
            timer = new Timer();
        }
        //if(task == null)
        task = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(1000);
            }
        };
        timer.scheduleAtFixedRate(task,0,1000);
    }

    /**
     * 结束定时任务
     */
    public void stop(){

        if (task != null) {
            task.cancel();
            task = null;
        }
        if(timer != null){
            timer.cancel();
            timer = null;
        }

    }

}
